﻿using DAO.db;
using Entity.shangping;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace DAO.shangping
{
    public class ShopCarDao
    {
       /// <summary>
       /// 保存商品到购物车
       /// </summary>
       /// <param name="shopCar"></param>
       /// <returns></returns>
       public int Save(ShopCar shopCar)
       {
           int ret = 0;
           if (string.IsNullOrEmpty(shopCar.ID))//如果没有ID，则表示添加
           {
               shopCar.ID = Guid.NewGuid().ToString();
               using (EFDbContext dbContext = new EFDbContext())
               {
                   dbContext.ShopCars.Add(shopCar);
                   dbContext.SaveChanges();
                   ret = 10;
               }
           }
           else//否则表示修改
           {
               using (EFDbContext dbContext = new EFDbContext())
               {
                   dbContext.Entry(shopCar).State = EntityState.Modified;
                   dbContext.SaveChanges();
                   ret = 10;
               }
           }
           return ret;
       }





       /// <summary>
       /// 购物车列表数据
       /// </summary>
       /// <param name="UserID">用户ID</param>
       /// <returns></returns>
       public List<ShopCar> GetList(string UserID)
       {
           List<ShopCar> pp = new List<ShopCar>();
           using (EFDbContext dbContext = new EFDbContext())
           {
               var query = dbContext.ShopCars.AsQueryable();

               if (!string.IsNullOrEmpty(UserID))
               {
                   query.Where(t => t.UserID == UserID);
               }
               pp = query.ToList();
           }
           return pp;
       }






       /// <summary>
       /// 删除购物车商品
       /// </summary>
       /// <param name="ID">购物车ID</param>
       /// <returns>1表示删除成功，否则删除失败</returns>
       public int transl(string ID)
       {
           int ret = 0;
           using (EFDbContext dbContext = new EFDbContext())
           {
               var g = dbContext.ShopCars.Find(ID);
               if (g != null)
               {
                   ////删除方式一
                   //dbContext.ShopCars.Attach(user);
                   //dbContext.ShopCars.Remove(user);
                   //删除方式二
                   dbContext.Entry(g).State = EntityState.Deleted;
                   dbContext.SaveChanges();
                   ret = 1;
               }

           }
           return ret;
       }






    }

}
